package com.atmilan.quartz.utils.product;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.atmilan.quartz.config.RestTemplateConfig;
import com.atmilan.quartz.model.dto.bellettini.BellettiniProductResDTO;
import com.atmilan.quartz.model.dto.coltorti.ColtortiProductResDTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * 拉取商品源数据
 */

@Slf4j
@Service
public class ColtortiProductUtil {

    @Autowired
    private RestTemplateConfig restTemplateConfig;
    @Value("${coltorti.username}")
    private String coltortiUsername;
    @Value("${coltorti.password}")
    private String coltortiPassword;
    @Value("${coltorti.url}")
    private String coltortiUrl;

    public List<ColtortiProductResDTO> selectColtortiPage() throws Exception {
        // 遍历数据
        List<ColtortiProductResDTO> coltortiProductResDTOs = null;
        try {
            String BASIC = "Basic {}";
            String auth = Base64.encode((coltortiUsername + ":" + coltortiPassword).getBytes());

            RestTemplate restTemplate = restTemplateConfig.restTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.TEXT_XML);
            headers.add("Authorization", StrUtil.format(BASIC, auth));
            HttpEntity<String> entity = new HttpEntity<String>(headers);
            ResponseEntity<String> response = restTemplate.exchange(coltortiUrl, HttpMethod.GET, entity, String.class);
            String[] resultArr = response.getBody().split("\\r?\\n");
            if (HttpStatus.OK != response.getStatusCode()) {
                JSONObject message = JSONObject.parseObject(response.getBody());
                String errorMessage = message.getString("error");

                log.info("--------------- coltorti获取商品列表异常{} ---------------", errorMessage);
            }
            coltortiProductResDTOs = new ArrayList<ColtortiProductResDTO>();
            for(int i=1; i<resultArr.length; i++) {
                // 替换规则
                char[] resultChar = resultArr[i].toCharArray();
                boolean isString = false;
                StringBuilder sb = new StringBuilder();
                for(int z=0; z<resultChar.length; z++) {
                    if("\"".equals(resultChar[z] + "")) {
                        isString = isString ? false : true;
                    }
                    if(";".equals(resultChar[z] + "") && isString) {
                        resultChar[z] = ",".charAt(0);
                    }
                    sb.append(resultChar[z]);
                }
                String[] tableContent = sb.toString().replaceAll("\"", "").split(";");
                if(43 != tableContent.length) {
                    continue;
                }
                ColtortiProductResDTO coltortiProductResDTO = new ColtortiProductResDTO();
                coltortiProductResDTO.setProductUrl(tableContent[0]);
                coltortiProductResDTO.setImage(tableContent[1]);
                coltortiProductResDTO.setImage1(tableContent[2]);
                coltortiProductResDTO.setImage2(tableContent[3]);
                coltortiProductResDTO.setImage3(tableContent[4]);
                coltortiProductResDTO.setBrand(tableContent[5]);
                coltortiProductResDTO.setSkuStyleisnow(tableContent[6]);
                coltortiProductResDTO.setSeason(tableContent[7]);
                coltortiProductResDTO.setYear(tableContent[8]);
                coltortiProductResDTO.setSkuSupplier(tableContent[9]);
                coltortiProductResDTO.setVariant(tableContent[10]);
                coltortiProductResDTO.setColorDetail(tableContent[11]);
                coltortiProductResDTO.setColorSupplier(tableContent[12]);
                coltortiProductResDTO.setMadeIn(tableContent[13]);
                coltortiProductResDTO.setMaterial(tableContent[14]);
                coltortiProductResDTO.setName(tableContent[15]);
                coltortiProductResDTO.setDescription(tableContent[16]);
                coltortiProductResDTO.setCategories(tableContent[17]);
                coltortiProductResDTO.setQty(Integer.parseInt(tableContent[18]));
                coltortiProductResDTO.setRetailPrice(tableContent[19]);
                coltortiProductResDTO.setDiscount(tableContent[20]);
                coltortiProductResDTO.setSizeInfo(tableContent[21]);
                coltortiProductResDTO.setSize(tableContent[22]);
                coltortiProductResDTO.setQtyDetail(tableContent[23]);
                coltortiProductResDTO.setBagLength(tableContent[24]);
                coltortiProductResDTO.setBagHeight(tableContent[25]);
                coltortiProductResDTO.setBagWeight(tableContent[26]);
                coltortiProductResDTO.setHandleHeight(tableContent[27]);
                coltortiProductResDTO.setShoulderBagLength(tableContent[28]);
                coltortiProductResDTO.setBeltLength(tableContent[29]);
                coltortiProductResDTO.setBeltHeight(tableContent[30]);
                coltortiProductResDTO.setAccessoryLength(tableContent[31]);
                coltortiProductResDTO.setAccessoryHeight(tableContent[32]);
                coltortiProductResDTO.setAccessoryWeight(tableContent[33]);
                coltortiProductResDTO.setHeelHeight(tableContent[34]);
                coltortiProductResDTO.setPlateauHeight(tableContent[35]);
                coltortiProductResDTO.setInsoleLength(tableContent[36]);
                coltortiProductResDTO.setColorStyleisnowIta(tableContent[37]);
                coltortiProductResDTO.setFta(tableContent[38]);
                coltortiProductResDTO.setEan(tableContent[39]);
                coltortiProductResDTO.setNomeIta(tableContent[40]);
                coltortiProductResDTO.setDescrizioneIta(tableContent[41]);
                coltortiProductResDTO.setStar(tableContent[42]);
                coltortiProductResDTO.setCreateTime(new Date());
                coltortiProductResDTOs.add(coltortiProductResDTO);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return coltortiProductResDTOs;
    }

    public static void main(String[] args) {
        String coltortiUsername = "prc";
        String coltortiPassword = "y73wbPPhtL";
        String coltortiUrl = "http://pim.coltorti.it:8080/csvExport/export/00000000000000000372/allProducts.csv";

        String BASIC = "Basic {}";
        String auth = Base64.encode((coltortiUsername + ":" + coltortiPassword).getBytes());

//        HttpHeaders headers = new HttpHeaders();
//        headers.setContentType(MediaType.TEXT_XML);
//        headers.add("Authorization", StrUtil.format(BASIC, auth));
//        HttpEntity<String> entity = new HttpEntity<String>(headers);


//        String s = HttpUtil.get(coltortiUrl, entity);
        cn.hutool.http.HttpRequest get = HttpUtil.createGet(coltortiUrl);
        get.contentType("text/xml");
        Map<String, String> head = new HashMap<>();
        head.put("Authorization", StrUtil.format(BASIC, auth));
        get.addHeaders(head);
        HttpResponse execute = get.execute();
        System.out.println();
        String s = new String(execute.bodyBytes());
        System.out.println();


//        ResponseEntity<String> response = restTemplate.exchange(coltortiUrl, HttpMethod.GET, entity, String.class);
//        String[] resultArr = response.getBody().split("\\r?\\n");
//        if (HttpStatus.OK != response.getStatusCode()) {
//            JSONObject message = JSONObject.parseObject(response.getBody());
//            String errorMessage = message.getString("error");
//
//            log.info("--------------- coltorti获取商品列表异常{} ---------------", errorMessage);
//        }
//        coltortiProductResDTOs = new ArrayList<ColtortiProductResDTO>();


    }

}
